package cc.customer.sendMsg;

import cc.customer.cAppNews.CAppNewsService;
import cc.customer.expCustomer.dao.ExEmpMapper;
import cc.customer.expCustomer.domain.ExEmp;
import cc.customer.SocketIo.SocketIOService;
import cc.customer.SocketIo.projo.PushMessage;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.utils.Utils;
import cc.customer.rabbit.dao.CconvNoticeMapper;
import cc.customer.rabbit.domain.CAppNews;
import cc.customer.rabbit.domain.CconvNotice;
import cc.customer.system.dao.DeptMapper;
import cc.customer.system.dao.UserMapper;
import cc.customer.system.domain.CDingConfig;
import cc.customer.system.domain.Dept;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.DingConfigServices;
import cc.customer.system.service.UserService;
import cc.customer.utils.MessageTemplate;
import com.alibaba.fastjson.JSONArray;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class SendMagRecevicer {

    private static final Logger logger = LoggerFactory.getLogger(SendMagRecevicer.class);

    /**
     * 一个部门消息推送当前人员
     **/
    @Autowired
    private UserService userService;
    @Autowired
    private DeptMapper deptMapper;

    /**
     * 推送记录的增加
     **/
    @Autowired
    private CconvNoticeMapper cconvNoticeMapper;


    @Autowired
    private CAppNewsService cAppNewsService;
    /**
     * 推送钉钉信息
     **/
    @Autowired
    private DingConfigServices dingConfigServices;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ExEmpMapper exEmpMapper;


    /**
     * 推送整个部门
     **/
    public synchronized void processDept(CconvNotice notice) {
        try {
            String uuid = Utils.getUUID();
            String cont = notice.getcConvCont();
            MyUser user = new MyUser();
            user.setDeptId(Long.valueOf(notice.getcConvDept()));
            user.setStatus("1");
            List<MyUser> myUsers = userService.findUserWithDept(user);
            List<String> username = new ArrayList<>();
            myUsers.forEach(userinfo -> {
                username.add(userinfo.getUsername());
            });
            PushMessage pushMessage = new PushMessage();
            pushMessage.setDeptUsers(username);
            pushMessage.setText(cont);
            pushMessage.setTitle(notice.getcConvTitle());
            pushMessage.setUuid(uuid);
           // socketIOService.pushMessageToDept(pushMessage);
            notice.setcConvSession(uuid);
            cconvNoticeMapper.insert(notice);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送给个人
     **/
    public void processUser(CconvNotice notice) {
        try {
            String uuid = Utils.getUUID();
            String cont = notice.getcConvCont();
            String userName = notice.getcConvUsers();
            logger.info("服务端推送给客户端 :【{}】", cont, userName);
            PushMessage pushMessage = new PushMessage();
            pushMessage.setUserid(userName);
            pushMessage.setText(cont);
            pushMessage.setTitle(notice.getcConvTitle());
            pushMessage.setUuid(uuid);
           // socketIOService.pushMessageToUser(pushMessage);
            cconvNoticeMapper.insert(notice);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送多个人
     **/
    public void processUsers(CconvNotice notice) {
        try {
            String uuid = Utils.getUUID();
            String cont = notice.getcConvCont();
            String userName = notice.getcConvUsers();
            logger.info("服务端推送给客户端 :【{}】", cont, userName);
            List<String> list = Arrays.asList(userName.split(","));
            PushMessage pushMessage = new PushMessage();
            pushMessage.setText(cont);
            pushMessage.setTitle(notice.getcConvTitle());
            pushMessage.setUuid(uuid);
            pushMessage.setDeptUsers(list);
            //socketIOService.pushMessageToOther(pushMessage);
            notice.setcConvSession(uuid);
            cconvNoticeMapper.insert(notice);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送月报
     **/
    public void processMonthReport(CconvNotice notice) {

        String cont = notice.getcConvCont();
        List<MyUser> myUsers = userService.selectAll();
        List<String> username = new ArrayList<>();
        myUsers.forEach(userinfo -> {
            username.add(userinfo.getUsername());
        });
        PushMessage pushMessage = new PushMessage();
        pushMessage.setText(cont);
        pushMessage.setTitle(notice.getcConvTitle());
        pushMessage.setUuid(notice.getcConvSession());
        pushMessage.setDeptUsers(username);
        //socketIOService.pushMessageToMonth(pushMessage);
        cconvNoticeMapper.insert(notice);
    }

    /**
     * 推送钉钉
     **/
    public void sendMsgForDingding(ExEmp exEmp,String types) {
        try {
            CDingConfig responseBo = dingConfigServices.selectAllCdingConfig(exEmp.getcExIntern(), exEmp.getcExDept(),types);
            if (responseBo != null) {
                String isTui = responseBo.getcExAithon();
                String isIntern = responseBo.getcExExname();
                if ("0".equals(isIntern)) {
                    if ("0".equals(isTui)) {
                        List<OapiMessageCorpconversationAsyncsendV2Request.Form> jsonArray = new ArrayList<>();

                        OapiMessageCorpconversationAsyncsendV2Request.Form map2 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
                        map2.setKey("姓名: ");
                        map2.setValue(exEmp.getcExName());

                        jsonArray.add(map2);

                        OapiMessageCorpconversationAsyncsendV2Request.Form map3 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
                        map3.setKey("电话: ");
                        map3.setValue(exEmp.getcExMobile());

                        jsonArray.add(map3);

                        OapiMessageCorpconversationAsyncsendV2Request.Form map4 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
                        map4.setKey( "微信: ");
                        map4.setValue( exEmp.getcExWechat());

                        jsonArray.add(map4);

                        OapiMessageCorpconversationAsyncsendV2Request.Form map5 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
                        map5.setKey( "QQ: ");
                        map5.setValue(exEmp.getcExQq());

                        jsonArray.add(map5);

                        OapiMessageCorpconversationAsyncsendV2Request.Form map6 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
                        map6.setKey("邮箱: ");
                        map6.setValue(exEmp.getcExEmail());

                        jsonArray.add(map6);

                        //推送钉钉
                        Dept dept = new Dept();
                        dept.setDeptId(Long.parseLong(exEmp.getcExDept()));
                        dept = deptMapper.selectOne(dept);
                        String deptName = dept.getDeptName();

                        OapiMessageCorpconversationAsyncsendV2Request.Form map1 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
                        map1.setKey("接收部门: ");
                        map1.setValue(deptName);

                        jsonArray.add(map1);
                        String content = exEmp.getcExRemarks().replaceAll("<br>", "\n");


                        if (!StringUtils.isEmpty(responseBo.getcExUser())) {
                            String users = "";

                            /**所有的推送人**/
                            String exUser = responseBo.getcExUser();
                            List<String> list = new ArrayList<>(Arrays.asList(exUser.split(",")));

                            List<String> list2 = new ArrayList<>(Arrays.asList(exUser.split(",")));

                            /**所有的已经推送的人**/
                            String exSUser = responseBo.getcExStuser();
                            /**已经更新的**/
                            List<String> listSUserNew = new ArrayList<>();

                            if (StringUtils.isEmpty(exSUser)) {
                                users = list.get(0);
                            } else {
                                /**如果不为空 则轮询下一个**/
                                List<String> listSUser = new ArrayList<>(Arrays.asList(exSUser.split(",")));
                                List<String> listAll = new ArrayList<>();
                                listSUser.forEach(allUsers -> {
                                    if (list.contains(allUsers)) {
                                        listAll.add(allUsers);
                                    }
                                });
                                list.removeAll(listAll);/**删除所有已经推送的信息**/
                                if (list.isEmpty()) {
                                    users = list2.get(0);
                                } else {
                                    listSUserNew.addAll(listAll);
                                    users = list.get(0);
                                }
                            }
                            listSUserNew.add(users);
                            /**更新数据**/
                            CDingConfig cDingConfig = new CDingConfig();
                            cDingConfig.setcExDept(exEmp.getcExDept());
                            cDingConfig.setcExName(exEmp.getcExIntern());
                            cDingConfig.setcExStuser(StringUtils.join(listSUserNew, ","));
                            cDingConfig.setcExType(types);
                            ResponseBo res = dingConfigServices.saveDingUserConfig(cDingConfig);

                            String type = "";
                            if("23".equals(exEmp.getcExDept())){
                                type = "isSi";
                            }else{
                                type = "noSi";
                            }

                            logger.error("更新了推送轮询" + res.toString() + "   更新的人员由：" + StringUtils.join(list, ",") +
                                    "  变更后的人员:" + StringUtils.join(listSUserNew, ","));


                            Example example= new Example(MyUser.class);
                            example.createCriteria().andEqualTo("dingUserid",users);
                            String name = userMapper.selectByExample(example).get(0).getNickname();
                            ResponseBo responseBo1 = MessageTemplate.sendAllCompnyMsg(jsonArray, users, content,type,exEmp.getcExUuid());
                            logger.error("钉钉推送接收人id："+users);
                            logger.error("推送钉钉信息:" + responseBo1.toString());

                            //极光推送
                            Example example1 = new Example(MyUser.class);
                            example1.createCriteria().andEqualTo("dingUserid",users);
                            MyUser user1 = userMapper.selectByExample(example1).get(0);
                            exEmp.setcExReceiver(user1.getUserUuid());

                            sendMsgToJiGuang(exEmp);
                        }
                    }
                } else {
                    /**白天推送*/
                    sendMsgToDingding(exEmp);
                }
            } else {
                /**白天推送*/
                sendMsgToDingding(exEmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 双重钉钉推送
     */
    public void sendMsgToDingding(ExEmp exEmp) {
        try {
            String dinguserid = "";
            if (!StringUtils.isEmpty(exEmp.getcExReceiver())) {
                Example example = new Example(MyUser.class);
                example.createCriteria().andEqualTo("userUuid", exEmp.getcExReceiver());
                List<MyUser> usersl = userMapper.selectByExample(example);
                dinguserid = usersl.get(0).getDingUserid();
            } else {
                StringBuffer bs = new StringBuffer();
                Example example1 = new Example(MyUser.class);
                example1.createCriteria().andEqualTo("deptId", exEmp.getcExDept()).andEqualTo("status",MyUser.STATUS_VALID);
                List<MyUser> usersl = userMapper.selectByExample(example1);
                for (MyUser u : usersl) {
                    bs.append(u.getDingUserid() + ",");
                }
                dinguserid = bs.substring(0, bs.lastIndexOf(","));
            }

            List<OapiMessageCorpconversationAsyncsendV2Request.Form> jsonArray = new ArrayList<>();

            OapiMessageCorpconversationAsyncsendV2Request.Form map2 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            map2.setKey("姓名: ");
            map2.setValue(exEmp.getcExName());

            jsonArray.add(map2);

            OapiMessageCorpconversationAsyncsendV2Request.Form map3 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            map3.setKey("电话: ");
            map3.setValue( exEmp.getcExMobile());

            jsonArray.add(map3);

            OapiMessageCorpconversationAsyncsendV2Request.Form map4 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            map4.setKey("微信: ");
            map4.setValue(exEmp.getcExWechat());

            jsonArray.add(map4);

            OapiMessageCorpconversationAsyncsendV2Request.Form map5 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            map5.setKey("QQ: ");
            map5.setValue(exEmp.getcExQq());

            jsonArray.add(map5);

            OapiMessageCorpconversationAsyncsendV2Request.Form map6 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            map6.setKey("邮箱: ");
            map6.setValue(exEmp.getcExEmail());

            jsonArray.add(map6);

            //推送钉钉
            Dept dept = new Dept();
            dept.setDeptId(Long.parseLong(exEmp.getcExDept()));
            dept = deptMapper.selectOne(dept);
            String deptName = dept.getDeptName();

            OapiMessageCorpconversationAsyncsendV2Request.Form  map1 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
            map1.setKey("接收部门: ");
            map1.setValue( deptName);

            jsonArray.add(map1);
            String content = exEmp.getcExRemarks().replaceAll("<br>", "\n");

            String type = "";
            if("23".equals(exEmp.getcExDept())){
                //思学中心
                type = "isSi";
            }else{
                type = "noSi";
            }
            logger.error("钉钉推送接收人id："+dinguserid);
            String exUuid = exEmp.getcExUuid();

            sendMsgToJiGuang(exEmp);
            ResponseBo responseBo1 = MessageTemplate.sendAllCompnyMsg(jsonArray, dinguserid, content,type,exUuid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 极光推送
     * @param exEmp  客户
     */
    public void sendMsgToJiGuang(ExEmp exEmp) {

        //推送用户的uuid
        String dinguserid = "";
        if (!StringUtils.isEmpty(exEmp.getcExReceiver())) {
            Example example = new Example(MyUser.class);
            example.createCriteria().andEqualTo("userUuid", exEmp.getcExReceiver());
            List<MyUser> usersl = userMapper.selectByExample(example);
            dinguserid = usersl.get(0).getUserUuid();
        } else {
            StringBuffer bs = new StringBuffer();
            Example example1 = new Example(MyUser.class);
            example1.createCriteria().andEqualTo("deptId", exEmp.getcExDept()).andEqualTo("status", MyUser.STATUS_VALID);
            List<MyUser> usersl = userMapper.selectByExample(example1);
            for (MyUser u : usersl) {
                bs.append(u.getUserUuid() + ",");
            }
            dinguserid = bs.substring(0, bs.lastIndexOf(","));
        }

        logger.error("极光推送的人员为："+dinguserid);
        List<String> list = new ArrayList<>(Arrays.asList(dinguserid.split(",")));

        for (String uuid : list){
                MyUser user1 = userService.findUserByUuids(uuid);
            //推送极光消息
            CAppNews cAppNews = new CAppNews();
            cAppNews.setcConvNtype("3");
            cAppNews.setcCousrsType(exEmp.getcESourType());
            cAppNews.setCusid(exEmp.getcExId()+"");
            cAppNews.setCustomerid(exEmp.getcExUuid());
            cAppNews.setCustomername(exEmp.getcExName());
            cAppNews.setcConvType("1");
            cAppNews.setcConvUsersName(user1.getNickname());
            cAppNews.setcConvUsers(user1.getUserUuid());
            cAppNews.setcConvTitle("推广资源");
            cAppNews.setcConvCont("新里程客户系统APP推送给了您客户为：" + exEmp.getcExName() + "电话：" + exEmp.getcExMobile());
            cAppNewsService.addCAppNews(cAppNews);
        }

    }
}
